//import * as dateFns from 'date-fns'
import { defaultsDeep } from 'lodash'
import config from '@/utils/config.js'
import { getMsgList } from '@/api/common.js'

//通知消息
const notice = {
	toast(title, duration = 2000) {
		uni.showToast({
			title,
			duration,
			icon: 'none'
		});
	},
	showLoading(title = '请稍后') {
		uni.showLoading({
			title,
			mask: true
		})
	},
	hideLoading() {
		uni.hideLoading()
	},
	alert(content, callback) {
		uni.showModal({
			content,
			confirmColor: constant.APP_DEFAULT_COLOR,
			showCancel: false,
			success() {
				callback && callback()
			}
		})
	},
	/**
	 * @param {Object} opt 
	 * content 内容 ，title 标题 ，cancelText 取消文本文字 confirmText 确认文字
	 * success 成功回调 
	 */
	confirm(content, ok, cancel, opt = {}) {
		const nOpt = Object.assign(opt, {
			cancelColor: constant.APP_DEFAULT_COLOR,
			confirmColor: constant.APP_DEFAULT_COLOR,
			content
		});
		nOpt.success = function(res) {
			if (res.confirm) ok && ok();
			else cancel && cancel();
		}
		uni.showModal(nOpt);
	}
}

//网络
const http = {
	merge(reqs) {
		getApp().globalData.disableLoading = true

		return new Promise((resolve, reject) => {
			notice.showLoading()
			Promise.all(reqs.map(p => p.catch(e => null))).then(res => {
				notice.hideLoading();
				getApp().globalData.disableLoading = false
				resolve(res)
			}).catch(err => {
				alert(1)
				notice.hideLoading();
				getApp().globalData.disableLoading = false
				reject(err)
			})
		})
	},
	spread(callback) {
		return function wrap(arr) {
			return callback.apply(null, arr);
		};
	}
}

// 公共
const utilities = {
	// 得到当前月份
	getQueryMonth(separator = '') {
		const now = new Date()
		return now.getFullYear() + separator + (now.getMonth() + 1).toString().padStart(2, '0')
	},
	// 格式化文章内容，去除html标签 保留指定长度字符
	formatActiveDesc(html ,len = 30) {
		if(!html) return ''
		
		html = html.replace(/<\/?[^>]*>/g,'')
		html = html.replace(/[ | ]*\n/g,'\n')
		html = html.replace(/&nbsp;/ig,'')
		
		if(html.length > len) {
			html = html.substring(0, len) + '...'
		}
		return html
	},
	// 转换菜单为树形结构
	transformToTreeFormat(data, setting = {}) {
		const defaultSetting = {
			isParent: 'isParent',
			childrenKey: 'children',
			nameKey: 'name',
			titleKey: 'title',
			idKey: 'id',
			pIdKey: 'parentId',
			levelKey: 'level',
			rootPId: null
		}
	    const sNodes = JSON.parse(JSON.stringify(data))
	    setting = defaultsDeep({}, setting, defaultSetting)
	    const idKey = setting.idKey
	    const pIdKey = setting.pIdKey
	    const childrenKey = setting.childrenKey
	
	    let i, j, l
	    if (!idKey || idKey === '' || !sNodes) { 
			return [] 
		}
	    if (sNodes instanceof Array) {
			const r = []
			const tmpMap = []
			for (i = 0, l = sNodes.length; i < l; i++) {
				tmpMap[sNodes[i][idKey]] = sNodes[i]
			}
	
			for (j = 0, l = sNodes.length; j < l; j++) {
				if (tmpMap[sNodes[j][pIdKey]] && sNodes[j][idKey] !== sNodes[j][pIdKey]) {
					if (!tmpMap[sNodes[j][pIdKey]][childrenKey]) {
						tmpMap[sNodes[j][pIdKey]][childrenKey] = []
					}
					tmpMap[sNodes[j][pIdKey]][childrenKey].push(sNodes[j])
				} else {
					r.push(sNodes[j])
				}
			}
			return r
	    } else {
			return [sNodes]
	    }
	}
}

// 业务相关
const business = {
	refreshMsgCount() {
		getMsgList().then(res=>{
			const count = res.data.pageResult.totalCount || 0
			
			if(count > 0) {
				uni.setTabBarBadge({
					index: 2,
					text: count < 100 ? count + '' : '99+'
				})
			} else {
				uni.removeTabBarBadge({
					index: 1
				})
			}
			
		})
	}
}

const file = {
	previewImage(fileId) {
		return config.baseUrl + '/platform/v3/file/preview' + "?attachmentId=" + fileId
	},
	getImage(picture) {
		return config.baseUrl + '/platform/v3' + picture
	},
	showImage(fileId) {
		uni.previewImage({
			urls: [this.previewImage(fileId)]
		})
	},
	checkFileType(fileName) {
		return (fileName).match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[1].toLowerCase()
	},
	checkIsImg(attachment) {
		const fileExtension = attachment.ext
		//const fileExtension = (fileName).match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[1].toLowerCase()
		return fileExtension === 'jpg' || fileExtension === 'jpeg' || fileExtension === 'png' || fileExtension === 'bmp' || fileExtension === 'gif'
	},
	checkIsAudio(attachment) {
		const fileExtension = attachment.ext
		//const fileExtension = (fileName).match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[1].toLowerCase()
		return fileExtension === 'mp3' || fileExtension === 'amr'
	},
	showOrDownload(fileId, attachment) {
		if(this.checkIsImg(attachment)) {			
			uni.previewImage({
				urls: [this.previewImage(fileId)]
			})
		} else {
			uni.downloadFile({
				url: this.downFileUrl(fileId)
			})
		}
	
	},
	downFileUrl(fileId){
		return config.baseUrl + '/platform/v3/file/download' + "?attachmentId=" + fileId
	},
	// 选择图片
	chooseImage(count = 1) {
		const limitType = ['image/jpeg', 'image/png', 'image/bmp']
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count,
				success({ tempFilePaths, tempFiles }) {
					const firstFile = tempFiles.find( r => limitType.includes(r.type) )
					if(!firstFile) {
						notice.toast('只允许上传 jpg; png; bmp 格式的图片')
						reject()						
					} else {
						const filePath = tempFilePaths[0]
						const fileName = firstFile.name
						resolve( { filePath, fileName, tempFilePaths, tempFiles } )
					}			
				},
				fail() {
					notice.toast('文件读取错误，请重试')
					reject()
				}
			})
		})
	},
	// 上传文件
	uploadFile(filePath, files) {
		uni.showLoading({
			title: '附件上传中',
			mask: true
		})
		return new Promise((resolve, reject) => {
			const params = {
				url: `${url_path.base_url}/appService/uploadWav.app`,
				name: 'file',
				filePath,
				success: (res) =>{
					const data = JSON.parse(res.data)
					getFileInfo(data.result.fileId).then(fileInfo=>{
						fileInfo.file_id = data.result.fileId
						resolve(fileInfo)
						uni.hideLoading()
					})			
				},
				fail() {
					notice.toast('上传失败，请稍后再试')
					uni.hideLoading()
					reject()
				}
			}
			
			if(filePath) {
				params.filePath = filePath
			} else {
				params.files = files
			}
			
			uni.uploadFile(params)
		})
	},
	// 选择图片并且上传
	async chooseAndUp() {
		const cImages = await this.chooseImage()
		return new Promise((resolve, reject)=>{
			this.uploadFile(cImages.filePath).then(res=>{
				resolve(res)
			}).catch(err=> reject(err))
		})
		console.log(cImages)
	},
	// 获取文件大小
	getFileSize(attachment){
		return parseFloat(attachment.file_size/1024).toFixed(2)
	}
}

export {
	notice,
	http,
	utilities,
	business,
	file
}
